package com.dnjn.happiness.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.SysSiteVO;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.system.domain.SysSite;
import com.dnjn.happiness.system.service.ISysDeptService;
import com.dnjn.happiness.system.service.ISysSiteService;
import com.dnjn.happiness.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 站点 二级部门单拉出来做站点 前端控制器
 * </p>
 *
 * @author Amber
 * @since 2023-10-05
 */
@Tag(name = "SysSite 站点 二级部门单拉出来做站点", description = "站点 二级部门单拉出来做站点")
@RestController
@RequestMapping("/sysSite")
public class SysSiteController extends BaseController {

    @Autowired
    protected ISysSiteService baseService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    @InnerAuth
    @GetMapping("/getInfoById/{siteId}")
    public R<SysSiteVO> getInfoById(@PathVariable Long siteId){
        SysSite one = baseService.lambdaQuery().eq(SysSite::getSiteId, siteId).one();
        SysSiteVO vo = new SysSiteVO();
        if (null != one){
            BeanUtils.copyBeanProp(vo,one);
        }
        return R.ok(vo);
    }

    @InnerAuth
    @GetMapping("/getSiteList")
    public R<List<SysSiteVO>> getSiteList(){
        List<SysSite> siteList = baseService.lambdaQuery().eq(SysSite::getDeleted, "0").list();
        List<SysSiteVO> voList = new ArrayList<>();
        siteList.forEach(item->{
            SysSiteVO vo = new SysSiteVO();
            BeanUtils.copyBeanProp(vo,item);
            voList.add(vo);
        });
        return R.ok(voList);
    }


    @GetMapping("/get/{id}")
    @RequiresPermissions("sys:sysSite:query")
    public AjaxResult get(@PathVariable Long id) {
        return success(baseService.getById(id));
    }

    @PostMapping("/add")
    @RequiresPermissions("sys:sysSite:add")
    public AjaxResult add(@Validated @RequestBody SysSite domain) {
        domain.setCreateBy(SecurityUtils.getUsername());
        //新增一条部门信息，部门的parent_id为总部的部门ID（parent_id为0的总部）
        if (!StringUtils.isEmpty(domain.getSiteName())) {

            SysDept dept = new SysDept();
            dept.setParentId(100L);
            dept.setDeptName(domain.getSiteName());
            deptService.insertDept(dept);
            domain.setDeptId(deptService.selectDeptByName(domain.getSiteName()).getDeptId());

        }else {
            return AjaxResult.error("厂区名称不能为空");
        }
        return toAjax(baseService.save(domain));
    }

    @PutMapping("/edit")
    @RequiresPermissions("sys:sysSite:edit")
    public AjaxResult edit(@Validated @RequestBody SysSite domain) {
        String siteName = domain.getSiteName();
        if (!StringUtils.isEmpty(siteName)) {

            SysDept oldDept = deptService.selectDeptById(domain.getDeptId());
            SysSite sysSite = baseService.lambdaQuery().eq(SysSite::getSiteId, domain.getSiteId()).one();
            oldDept.setDeptName(domain.getSiteName());
            deptService.updateDept(oldDept);

        }else {
            return AjaxResult.error("厂区名称不能为空");
        }

        return toAjax(baseService.updateById(domain));
    }

    @DeleteMapping("/{pkIds}")
    @RequiresPermissions("sys:sysSite:remove")
    public AjaxResult remove(@PathVariable Long[] pkIds) {
        for (Long pkId : pkIds) {
            SysSite sysSite = baseService.lambdaQuery().eq(SysSite::getSiteId, pkId).one();
            Long deptId = sysSite.getDeptId();
            SysDept sysDept = deptService.selectDeptById(deptId);
            if (("2").equals(sysDept.getDelFlag())){
                baseService.deleteSite(pkId);
            }else {
                return AjaxResult.error("当前厂区存在关联部门信息!");
            }
        }
        return success();
    }

    @PostMapping("/page")
    @RequiresPermissions("sys:sysSite:list")
    public AjaxResult page(@RequestBody SysSite domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
        Page<SysSite> list = baseService.page(page, Wrappers.query(domain).eq("deleted","0"));
        return success(list);
    }

    @PostMapping("/export")
    @RequiresPermissions("sys:sysSite:export")
    public void export(HttpServletResponse response, SysSite domain) {
        List<SysSite> list = baseService.list(Wrappers.query(domain));
        ExcelUtil<SysSite> util = new ExcelUtil<SysSite>(SysSite.class);
        util.exportExcel(response, list, "参数数据");
    }

    /**
     * 获取当前用户的站点信息
     */
    @GetMapping("/getUserSiteInfo")
    public AjaxResult getUserSiteInfo(){
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        if (null == sysUser){
            return AjaxResult.error("查询用户信息失败!");
        }
        Long deptId = sysUser.getDeptId();
        AjaxResult ajax = new AjaxResult();
        if (!ObjectUtils.isEmpty(deptId)){
            SysDept sysDept = deptService.selectDeptById(deptId);
            String ancestors = sysDept.getAncestors();
            String[] strings = ancestors.split(",");
            List<SysSite> sysSiteList = baseService.lambdaQuery().eq(SysSite::getDeleted,"0").list();
            if (sysSiteList.size() >0 && strings.length > 0){
                for (String str : strings) {
                    for (SysSite site : sysSiteList) {
                        if (site.getDeptId().equals(Long.parseLong(str)) || site.getDeptId().equals(deptId)){
                            ajax.put("code",200);
                            return ajax.put("site",site);
                        }
                    }
                }
            }


        }else {
            return ajax.put("site",new SysSite());
        }
        return ajax.put("site",new SysSite());
    }


    /**
     * 后台管理总管理员查看所有厂区列表
     * @return
     */
    @GetMapping("/siteListAll")
    @RequiresPermissions("sys:sysSite:query")
    public AjaxResult siteListAll() {
        List<SysSite> siteList = baseService.lambdaQuery().eq(SysSite::getDeleted, "0").list();
        return success(siteList);
    }


    /**
     *  总管理员查看厂区快乐值报表
     */
    @GetMapping("/siteAvgScore")
    public AjaxResult siteAvgScore(@RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String startTime, @RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String endTime){
        //如果两个日期为空时，默认获取当前日期前一个月的
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            LocalDateTime endLocalDateTime = LocalDateTime.now();
            LocalDateTime startLocalDateTime = LocalDateTime.now().minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTime = formatter.format(startLocalDateTime);
            endTime = formatter.format(endLocalDateTime);
        }
        List<SysSite> sysSiteList = baseService.siteAvgScore(startTime,endTime);
        return success(sysSiteList);
    }


}